package com.finger.forest;

import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.BitmapDrawable;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.core.content.ContextCompat;

import com.esri.arcgisruntime.ArcGISRuntimeEnvironment;
import com.esri.arcgisruntime.concurrent.ListenableFuture;
import com.esri.arcgisruntime.data.Feature;
import com.esri.arcgisruntime.data.FeatureCollection;
import com.esri.arcgisruntime.data.FeatureCollectionTable;
import com.esri.arcgisruntime.data.Field;
import com.esri.arcgisruntime.geometry.Envelope;
import com.esri.arcgisruntime.geometry.GeometryType;
import com.esri.arcgisruntime.geometry.Point;
import com.esri.arcgisruntime.geometry.SpatialReferences;
import com.esri.arcgisruntime.layers.FeatureCollectionLayer;
import com.esri.arcgisruntime.mapping.ArcGISMap;
import com.esri.arcgisruntime.mapping.Basemap;
import com.esri.arcgisruntime.mapping.GeoElement;
import com.esri.arcgisruntime.mapping.view.Callout;
import com.esri.arcgisruntime.mapping.view.DefaultMapViewOnTouchListener;
import com.esri.arcgisruntime.mapping.view.Graphic;
import com.esri.arcgisruntime.mapping.view.GraphicsOverlay;
import com.esri.arcgisruntime.mapping.view.IdentifyGraphicsOverlayResult;
import com.esri.arcgisruntime.mapping.view.LocationDisplay;
import com.esri.arcgisruntime.mapping.view.MapView;
import com.esri.arcgisruntime.symbology.PictureMarkerSymbol;
import com.esri.arcgisruntime.symbology.SimpleRenderer;
import com.esri.arcgisruntime.symbology.TextSymbol;
import com.finger.forest.base.BaseActivity;
import com.finger.forest.base.BaseView;
import com.finger.forest.base.CommonKey;
import com.finger.forest.base.ResponseTag;
import com.finger.forest.base.SystemConfig;
import com.finger.forest.custom.MyDialog;
import com.finger.forest.http.presenter.RegisterPresenter;
import com.finger.forest.model.FzHotspot;
import com.finger.forest.utils.ClickUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ExecutionException;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * 热点核查
 */
public class HotCheckActivity extends BaseActivity<RegisterPresenter> implements BaseView {

    private static final String TAG = "HotCheckActivity";

    /**
     * 返回
     */
    @BindView(R.id.btn_back)
    ImageView backIv;

    /**
     * 历史轨迹
     */
    @BindView(R.id.btn_operate)
    Button operateBtn;

    private MapView mMapView;

    //经度
    private String longitude;

    //纬度
    private String latitude;

    //热点ID（界面传值）
    private String hId;

    //热点名称
    private String hHotspotName;

    //热点编号
    private String hHotspotNo;

    private Callout mCallout;

    private MyDialog myDialog;

    private LocationDisplay mLocationDisplay;

    private FzHotspot hotDetail;

    private int type = 0;//反馈标识 0：未反馈；1：已反馈。


    /**
     * 弹框布局
     */
    LinearLayout layoutHotContent;

    @Override
    protected int setView() {
        return R.layout.activity_hot_check;
    }

    @Override
    protected void receiveData() {

    }

    @Override
    protected void initializeView() {
        //接收热点经纬度
        Intent intent=getIntent();
        type = intent.getIntExtra("type",0);
        hId = intent.getStringExtra("hId");
        mMapView = findViewById(R.id.mapView);

        //获取热点详情
        getHotDetailById();
    }

    @Override
    protected void loadDataFromServer() {

    }

    /**
     * 添加热点图标
     */
    private void createPointGraphics() {
        GraphicsOverlay mGraphicsOverlay = new GraphicsOverlay();
        mMapView.getGraphicsOverlays().add(mGraphicsOverlay);

        Point point2 = new Point(Double.parseDouble(longitude), Double.parseDouble(latitude), SpatialReferences.getWgs84());
        BitmapDrawable bitmapDrawable = (BitmapDrawable) ContextCompat.getDrawable(this, R.drawable.ic_fire);
        PictureMarkerSymbol pms = new PictureMarkerSymbol(bitmapDrawable);
        Graphic pointGraphic2 = new Graphic(point2, pms);
        mGraphicsOverlay.getGraphics().add(pointGraphic2);

        //定位热点位置
        //mMapView.setViewpointCenterAsync(point2);
    }

    private void setupMap() {
        if (mMapView != null) {
            ArcGISRuntimeEnvironment.setLicense(CommonKey.LICENSE);
            mMapView.setAttributionTextVisible(false);
            Basemap.Type basemapType = Basemap.Type.IMAGERY;
            ArcGISMap map = new ArcGISMap(basemapType, Double.parseDouble(latitude), Double.parseDouble(longitude), SystemConfig.mapLevel);
            mMapView.setMap(map);
        }

        mMapView.setOnTouchListener(new DefaultMapViewOnTouchListener(HotCheckActivity.this, mMapView) {
            @Override
            public boolean onSingleTapUp(MotionEvent e) {
                Log.i(TAG,e.getX()+","+e.getY());
                Log.i(TAG,"点击");
                //获取屏幕点击坐标
                android.graphics.Point mapPoint =  new android.graphics.Point((int)e.getX(),(int)e.getY());
                //将屏幕坐标 传入 identifyGraphicsOverlaysAsync （屏幕坐标，范围，包括图形和弹出窗口时为false，最大检索数）
                final ListenableFuture<List<IdentifyGraphicsOverlayResult>> listListenableFuture = this.mMapView.identifyGraphicsOverlaysAsync(mapPoint,12, false, 5);
                //this.mMapView.identifyLayerAsync(mMapView.getMap().getOperationalLayers(),mapPoint,12, false, 5);
                //添加点击事件
                listListenableFuture.addDoneListener(new Runnable() {
                    @Override
                    public void run() {
                        try {
                            //获取点击的范围列表
                            List<IdentifyGraphicsOverlayResult> identifyLayerResults = listListenableFuture.get();
                            //循环图层
                            for (IdentifyGraphicsOverlayResult identifyLayerResult : identifyLayerResults) {
                                //循环所点击要素
                                for (final GeoElement geoElement : identifyLayerResult.getGraphics()) {
                                    Envelope tEnvelope = geoElement.getGeometry().getExtent();
                                    Point tPoint = tEnvelope.getCenter();
                                    Log.e(TAG,"当前点击的："+tPoint);

                                    layoutHotContent = (LinearLayout)LayoutInflater.from(HotCheckActivity.this).inflate(R.layout.dialog_content_hot, null);

                                    //设置弹框值
                                    setLayoutContent();

                                    //弹框
                                    myDialog=new MyDialog(HotCheckActivity.this,R.style.MyDialog);
                                    myDialog.setTitle("热点信息");
                                    myDialog.setLayout(layoutHotContent);
                                    if (type == 0){
                                        myDialog.setYesOnclickListener("核查", new MyDialog.onYesOnclickListener() {
                                            @Override
                                            public void onYesOnclick() {
                                                Intent intent = new Intent(HotCheckActivity.this, HotCheckFeedbackActivity.class);
                                                intent.putExtra("hId", hId);//热点ID
                                                intent.putExtra("longitude", longitude);//经度
                                                intent.putExtra("latitude", latitude);//纬度
                                                intent.putExtra("hHotspotNo", hHotspotNo);//热点编号
                                                startActivity(intent);
                                                finish();
                                            }
                                        });
                                    } else {
                                        myDialog.setYesOnclickListener("已核查", new MyDialog.onYesOnclickListener() {
                                            @Override
                                            public void onYesOnclick() {
                                                myDialog.dismiss();
                                            }
                                        });
                                    }

                                    myDialog.setNoOnclickListener("取消", new MyDialog.onNoOnclickListener() {
                                        @Override
                                        public void onNoClick() {
                                            myDialog.dismiss();
                                        }
                                    });
                                    myDialog.show();


                                }
                            }
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        } catch (ExecutionException e) {
                            e.printStackTrace();
                        }
                    }
                });
                return super.onSingleTapUp(e);
            }
        });
    }

    //获取热点详情
    private void getHotDetailById() {
        Map<String, Object> maps = new HashMap<>();
        maps.put("Id",hId);
        presenter.queryHotDetail(maps);//查询热点核查详情
    }

    //创建要素集合
    FeatureCollection featureCollection = new FeatureCollection();
    //创建要素集合图层
    FeatureCollectionLayer featureCollectionLayer = new FeatureCollectionLayer(featureCollection);

    //添加热点和巡护员位置
    private void createFeatureCollection() {
        //将图层添加到地图
        mMapView.getMap().getOperationalLayers().add(featureCollectionLayer);
        createPointTable(featureCollection);
    }

    //自定义图标
    private SimpleRenderer getDrawableIcon(int draIcon){
        BitmapDrawable bitmapDrawable = (BitmapDrawable) ContextCompat.getDrawable(this, draIcon);
        PictureMarkerSymbol pms = new PictureMarkerSymbol(bitmapDrawable);
        SimpleRenderer renderer = new SimpleRenderer(pms);
        return renderer;
    }

    /**
     * 添加热点名称
     * @param featureCollection
     */
    private void createPointTable(FeatureCollection featureCollection) {

        List<Field> pointFields = new ArrayList<>();
        pointFields.add(Field.createString("Place", "Place Name", 50));

        //------ 文字 start--------
        //要素集合table
        FeatureCollectionTable pointsTableT = new FeatureCollectionTable(pointFields, GeometryType.POINT, SpatialReferences.getWgs84());
        TextSymbol textSymbol = new TextSymbol(10, hHotspotName, Color.WHITE, TextSymbol.HorizontalAlignment.CENTER, TextSymbol.VerticalAlignment.TOP);
        textSymbol.setOffsetY(-10);
        textSymbol.setFontFamily("DroidSansFallback.ttf");
        SimpleRenderer renderer = new SimpleRenderer(textSymbol);
        pointsTableT.setRenderer(renderer);

        // Malibu Pier
        Map<String, Object> attributesT = new HashMap<>();
        attributesT.put(pointFields.get(0).getName(), "Malibu Pier");
        Point pointT = new Point(Double.parseDouble(longitude), Double.parseDouble(latitude), SpatialReferences.getWgs84());

        List<Feature> featuresT = new ArrayList<>();
        featuresT.add(pointsTableT.createFeature(attributesT, pointT));

        pointsTableT.addFeaturesAsync(featuresT);

        //热点
        featureCollection.getTables().add(pointsTableT);
        //------ 文字 end--------

    }

    /**
     * 定位巡护员位置
     * @param featureCollection
     * @param longtitude
     * @param latitude
     */
    private void createPointTablePeople(FeatureCollection featureCollection,double longtitude, double latitude) {

        List<Field> pointFields = new ArrayList<>();
        pointFields.add(Field.createString("Place", "Place Name", 50));

        //要素集合table
        FeatureCollectionTable pointsTable1 = new FeatureCollectionTable(pointFields, GeometryType.POINT, SpatialReferences.getWgs84());
        pointsTable1.setRenderer(getDrawableIcon(R.drawable.ic_people));

        // Malibu Pier
        Map<String, Object> attributes2 = new HashMap<>();
        attributes2.put(pointFields.get(0).getName(), "Malibu Pier");
        Point point2 = new Point(longtitude, latitude, SpatialReferences.getWgs84());

        List<Feature> features2 = new ArrayList<>();
        features2.add(pointsTable1.createFeature(attributes2, point2));

        pointsTable1.addFeaturesAsync(features2);
        //巡护员
        featureCollection.getTables().add(pointsTable1);
    }

    @OnClick({R.id.btn_back, R.id.btn_operate })
    public void onClick(View v) {
        if (ClickUtils.isFastClick()) { //防止重复点击
            switch (v.getId()) {

                //返回
                case R.id.btn_back:
                    finish();
                    break;

                //开始出发、开始反馈
                case R.id.btn_operate:
                    if (operateBtn.getText().equals("开始出发")) {
                        operateBtn.setText("开始反馈");
                        //路线导航
                        //..
                    } else if (operateBtn.getText().equals("开始反馈")) {
                        Intent intent = new Intent(HotCheckActivity.this, HotCheckFeedbackActivity.class);
                        intent.putExtra("hId", hId);//热点ID
                        intent.putExtra("longitude", longitude);//经度
                        intent.putExtra("latitude", latitude);//纬度
                        intent.putExtra("hHotspotNo", hHotspotNo);//热点编号
                        startActivity(intent);
                        finish();
                    }
                    break;

                default:
                    break;
            }
        }
    }

    @Override
    public void onPause() {
        super.onPause();
        // pause MapView
        mMapView.pause();
    }

    @Override
    public void onResume() {
        super.onResume();
        // resume MapView
        mMapView.resume();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        // dispose MapView
        mMapView.dispose();
    }

    private void setLayoutContent(){
        TextView hotLongtitudeTv = layoutHotContent.findViewById(R.id.hot_longtitude);//经度
        TextView hotLatitudeTv = layoutHotContent.findViewById(R.id.hot_latitude);//纬度
        TextView hotCodeTv = layoutHotContent.findViewById(R.id.hot_code);//编号
        TextView hotLevelTv = layoutHotContent.findViewById(R.id.hot_level);//热点强度
        TextView hotCloudTv = layoutHotContent.findViewById(R.id.hot_is_cloud);//有无云烟
        TextView hotContinuaCtionTv = layoutHotContent.findViewById(R.id.hot_is_continuation);//是否连续
        TextView hotLandTypeTv = layoutHotContent.findViewById(R.id.hot_land_type);//地类
        TextView hotRegionTv = layoutHotContent.findViewById(R.id.hot_region);//所在区县
        TextView hotPositionTv = layoutHotContent.findViewById(R.id.hot_position);//所在位置
        TextView hotTimeTv = layoutHotContent.findViewById(R.id.hot_time);//报告时间

        hotLongtitudeTv.setText(hotDetail.gethLongitude().toString());
        hotLatitudeTv.setText(hotDetail.gethLatitude().toString());
        hotCodeTv.setText(hotDetail.gethHotspotNo());
        hotLevelTv.setText(hotDetail.gethValue()==null?"未知":hotDetail.gethValue().toString());
        hotCloudTv.setText(hotDetail.gethIsCloub()==null?"未知":hotDetail.gethIsCloub());
        hotContinuaCtionTv.setText(hotDetail.gethIsContinuation()==null?"未知":hotDetail.gethIsContinuation());
        hotLandTypeTv.setText(hotDetail.gethLandType()==null?"未知":hotDetail.gethLandType());
        hotRegionTv.setText(hotDetail.gethRegionId());
        hotPositionTv.setText(hotDetail.gethHotspotLoc());
        hotTimeTv.setText(hotDetail.gethReportTime());
    }

    @Override
    public void onSuccess(Object model, int tag, String msg) {

        switch (tag) {

            //热点核查详情
            case ResponseTag.QUERY_HOT_DETAIL:
                hotDetail = (FzHotspot) model;
                longitude = hotDetail.gethLongitude().toString();
                latitude = hotDetail.gethLatitude().toString();
                hHotspotName = hotDetail.gethCondition()==null?"":hotDetail.gethCondition().toString();
                hHotspotNo = hotDetail.gethHotspotNo();

                //初始化地图
                setupMap();

                //添加热点和巡护员位置
                createFeatureCollection();

                //添加热点图标
                createPointGraphics();

                break;

            default:
                break;
        }
    }

    @Override
    public void onError(int errcode, int tag, String message) {

    }
}
